package cn.fj.big.spring.httpclient.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;

/**
 * Created by LiJianXin on 2019/3/29 0029.
 */
@Configurable
public class HttpClientConfig {

	@Autowired
	private HttpClientProperties httpClientProperties;

	@Bean
	public RequestConfig requestConfig() {
		RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
		//指从连接池获取连接的超时时间
		requestConfigBuilder.setConnectionRequestTimeout(httpClientProperties.getRequestConfig().getConnectionRequestTimeout());
		//指客户端和服务器建立连接的超时时间
		requestConfigBuilder.setConnectTimeout(httpClientProperties.getRequestConfig().getConnectTimeout());
		//指客户端从服务器下载数据（或页面）时，两个数据包之间的最大时间间隔
		requestConfigBuilder.setSocketTimeout(httpClientProperties.getRequestConfig().getSocketTimeout());
		return requestConfigBuilder.build();
	}

	@Bean
	public HttpClientConnectionManager connectionManager() {
		PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
		//连接池最大容量（即全部路由的总连接数）
		httpClientConnectionManager.setMaxTotal(httpClientProperties.getConnectionManager().getMaxTotal());
		//每个路由的默认最大连接数
		httpClientConnectionManager.setDefaultMaxPerRoute(httpClientProperties.getConnectionManager().getDefaultMaxPerRoute());
		//如果对某个站点的连接数需求比较大，可以单独设置其最大连接数
		//httpClientConnectionManager.setMaxPerRoute();
		return httpClientConnectionManager;
	}

	@Bean
	public HttpClient httpClient() {
		return HttpClientBuilder.create()
				.setConnectionManager(connectionManager())
				.setDefaultRequestConfig(requestConfig())
				.build();
	}
}
